// 🚀 PWA Service Worker - 精英杂志
// 版本：v1.0.0
// 功能：离线缓存、推送通知、后台同步

const CACHE_NAME = 'elite-magazine-v2';
const RUNTIME_CACHE = 'elite-magazine-runtime';
const API_CACHE = 'elite-magazine-api';

// 📦 核心资源缓存
const CORE_ASSETS = [
  '/',
  '/index.html',
  '/admin.html',
  '/css/style.css',
  '/css/magazine.css',
  '/css/custom.css',
  '/js/mirror-config.js',
  '/js/main.js',
  '/static/vendor/bootstrap-lite.css',
  '/static/vendor/bootstrap-lite.min.js',
  '/manifest.json',
  '/images/logo.png',
  '/images/icons/icon-192x192.png',
  '/images/icons/icon-512x512.png',
  '/images/icons/icon-144x144.png'
];

// 📱 文章和API缓存策略
const API_URLS = [
  '/api/posts',
  '/api/articles',
  '/index.json',
  '/api/subscriptions'
];

// 🖼️ 图片和媒体资源
const IMAGE_URLS = [
  '/images/',
  '/images/icons/',
  '/images/screenshots/',
  '/images/widgets/'
];

// 📦 安装事件 - 缓存资源
self.addEventListener('install', event => {
  event.waitUntil(
    Promise.all([
      // 缓存核心资源
      caches.open(CACHE_NAME)
        .then(cache => {
          console.log('📦 缓存核心资源中...');
          return cache.addAll(CORE_ASSETS);
        }),
      // 预缓存API数据
      caches.open(API_CACHE)
        .then(cache => {
          console.log('📱 缓存API数据...');
          return cache.addAll(API_URLS);
        })
    ])
    .then(() => {
      console.log('✅ 资源缓存完成');
      return self.skipWaiting();
    })
  );
});

// 🔄 激活事件 - 清理旧缓存
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CACHE_NAME && 
              cacheName !== RUNTIME_CACHE && 
              cacheName !== API_CACHE) {
            console.log('🗑️ 删除旧缓存:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    }).then(() => {
      console.log('🔄 Service Worker 激活完成');
      return self.clients.claim();
    })
  );
});

// 🌐 网络请求拦截 - 智能缓存策略
self.addEventListener('fetch', event => {
  const { request } = event;
  const url = new URL(request.url);

  // 📰 文章API - 网络优先，缓存回退
  if (url.pathname.includes('/api/posts') || 
      url.pathname.includes('/api/articles') ||
      url.pathname.includes('/index.json')) {
    event.respondWith(
      fetch(request)
        .then(response => {
          // 缓存成功的响应
          const responseClone = response.clone();
          caches.open(API_CACHE).then(cache => {
            cache.put(request, responseClone);
          });
          return response;
        })
        .catch(() => {
          // 离线时返回缓存
          return caches.match(request).then(cachedResponse => {
            if (cachedResponse) {
              return cachedResponse;
            }
            // 如果没有缓存，返回离线页面
            return caches.match('/offline.html');
          });
        })
    );
    return;
  }

  // 🖼️ 图片资源 - 缓存优先，网络回退
  if (request.destination === 'image' || 
      url.pathname.includes('/images/')) {
    event.respondWith(
      caches.match(request)
        .then(response => {
          if (response) {
            return response;
          }
          return fetch(request).then(fetchResponse => {
            // 缓存新图片
            if (fetchResponse.status === 200) {
              const responseToCache = fetchResponse.clone();
              caches.open(RUNTIME_CACHE).then(cache => {
                cache.put(request, responseToCache);
              });
            }
            return fetchResponse;
          });
        })
        .catch(() => {
          // 返回占位图片
          return caches.match('/images/placeholder.png');
        })
    );
    return;
  }

  // 📱 CSS/JS资源 - 缓存优先
  if (request.destination === 'style' || 
      request.destination === 'script' ||
      url.pathname.includes('.css') ||
      url.pathname.includes('.js')) {
    event.respondWith(
      caches.match(request)
        .then(response => {
          return response || fetch(request).then(fetchResponse => {
            if (fetchResponse.status === 200) {
              const responseToCache = fetchResponse.clone();
              caches.open(CACHE_NAME).then(cache => {
                cache.put(request, responseToCache);
              });
            }
            return fetchResponse;
          });
        })
    );
    return;
  }

  // 🌐 其他资源 - 网络优先策略
  event.respondWith(
    fetch(request)
      .then(response => {
        // 检查响应是否有效
        if (!response || response.status !== 200 || response.type !== 'basic') {
          return response;
        }

        // 克隆响应并缓存
        const responseToCache = response.clone();
        caches.open(RUNTIME_CACHE).then(cache => {
          cache.put(request, responseToCache);
        });

        return response;
      })
      .catch(() => {
        return caches.match(request).then(cachedResponse => {
          if (cachedResponse) {
            return cachedResponse;
          }
          // 如果没有缓存，返回离线页面
          if (request.destination === 'document') {
            return caches.match('/offline.html');
          }
          return new Response('离线模式 - 内容不可用', {
            status: 503,
            statusText: 'Service Unavailable',
            headers: new Headers({
              'Content-Type': 'text/plain'
            })
          });
        });
      })
  );
});

// 🔔 推送通知
self.addEventListener('push', event => {
  const options = {
    body: '您有新的文章更新！',
    icon: '/images/icons/icon-192x192.png',
    badge: '/images/icons/icon-72x72.png',
    vibrate: [200, 100, 200],
    tag: 'new-article',
    actions: [
      {
        action: 'read',
        title: '立即阅读',
        icon: '/images/icons/read.png'
      },
      {
        action: 'later',
        title: '稍后阅读',
        icon: '/images/icons/later.png'
      }
    ]
  };

  event.waitUntil(
    self.registration.showNotification('精英杂志', options)
  );
});

// 🎯 通知点击事件
self.addEventListener('notificationclick', event => {
  event.notification.close();

  if (event.action === 'read') {
    // 立即阅读
    event.waitUntil(
      clients.openWindow('/')
    );
  } else if (event.action === 'later') {
    // 添加到稍后阅读
    event.waitUntil(
      clients.openWindow('/admin.html')
    );
  } else {
    // 默认打开应用
    event.waitUntil(
      clients.openWindow('/')
    );
  }
});

// 📊 后台同步
self.addEventListener('sync', event => {
  if (event.tag === 'sync-subscriptions') {
    event.waitUntil(syncSubscriptions());
  }
});

// 🔄 同步订阅数据
async function syncSubscriptions() {
  try {
    const cache = await caches.open(CACHE_NAME);
    const response = await fetch('/api/subscriptions/sync');
    
    if (response.ok) {
      const data = await response.json();
      await cache.put('/api/subscriptions', new Response(JSON.stringify(data)));
      console.log('✅ 订阅数据同步完成');
    }
  } catch (error) {
    console.log('❌ 同步失败:', error);
  }
}

// 🎯 消息通信
self.addEventListener('message', event => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
  
  if (event.data && event.data.type === 'GET_VERSION') {
    event.ports[0].postMessage({
      version: CACHE_NAME,
      timestamp: new Date().toISOString()
    });
  }
});